{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  字典"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典概述："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">* dict概述：字典是一种key - value 的数据类型，又叫做键/值对，使用键值对(key-value)方式存储数据。\n",
    "         字典= {字段名1：字段值，字段名2：字段值，字段名3：字段值}  \n",
    ">* dict中key的特点:\n",
    "             1.字典是无序的，但是key是唯一的，不可变性的。如果重复的最后的一个键值对会替换前面的，值不需要唯一。\n",
    "             2.key值必须是不可变的数据类型:int float str tuple\n",
    "             3.list是可变的，不能作key值使用\n",
    ">* dict中value的特点：\n",
    "                     value的类型可以是任意类型的，可以重复\n",
    ">* dict的特点：\n",
    "                     1、无序的集合\n",
    "                     2、可变的集合"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 基本操作："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 创建空的字典\n",
    "* 通过构造函数\n",
    "#>>>d = dict()\n",
    "* 直接通过符号\n",
    "#>>> d = {}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 创建非空字典\n",
    "* 通过构造函数，直接从key-value对中创建字典\n",
    "#>>>d = dict([('苹果','apple'),('香蕉','banana')])\n",
    "* 直接通过符号创建\n",
    "#>>>d = {'苹果':'apple','香蕉':'banana'}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典——访问字典里的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 字典，字典里的值的访问用: 字典名称 [ key ]\n",
    ">>> dict={'Name':'Zara','Age':7,'Class':'First'}\n",
    ">>>print(\"dict[Name]:\",dict['Name'])\n",
    ">>>dict['Name']:Zara\n",
    ">>>\n",
    ">>>print(\"dict['Age']:\",dict['Age'])\n",
    "dicr['Age']:7\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 向字典添加新内容的方法是增加新的键/值对，修改或删除已有键/值对。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 修改字典——增加"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict['Age']: 8\n"
     ]
    }
   ],
   "source": [
    "dict={'Name':'Zara','Age':7,'Class':'First'}\n",
    "dict['Age'] = 8\n",
    "dict['School'] = \"RUNOOB\"\n",
    "print(\"dict['Age']:\",dict['Age'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict['school']: RUNOOB\n"
     ]
    }
   ],
   "source": [
    "print(\"dict['school']:\",dict['School'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 修改字典——删除:能删单一的元素也能清空字典，清空只需一项操作。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Age': 7, 'Class': 'First'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict={'Name':'Zara','Age':7,'Class':'First'}\n",
    "del dict['Name']\n",
    "dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict.clear()\n",
    "dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del dict\n",
    "dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典的键入形式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#* 字典的键入形式要尽量的简单易懂\n",
    "#1\n",
    "person3 = {\n",
    "    \"name\":\"游鸽\",\n",
    "    \"Gender\":\"Male\",\n",
    "    \"Occupation\":\"Researcher\"\n",
    "    \"Home Planet\":\"Betelgeuce Seven\"\n",
    "}\n",
    "#2\n",
    "person4 ={\"name\":\"游鸽\",\"Gender\":\"Male\",\"Occupation\":\"Researcher\",\"Home Planet\":\"Betelgeuce Seve\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典的嵌套——访问一个复杂的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#字典嵌套就是字典中还有字典，就是多级字典\n",
    "FamousDict = {\n",
    "  '薛之谦':{\n",
    "    '身高':178,\n",
    "    '体重':130,\n",
    "    '口头禅':['你神经病啊！','我不要面子啊'] \n",
    "},\n",
    "  '吴青峰':{\n",
    "  '身高':170,\n",
    "    '体重':120,\n",
    "    '口头禅':['我叫吴青峰','你好']\n",
    "  }\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典中如何增加一个新的键值对\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': '游鸽', 'Gender': 'Male'}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#向字典中增加一个键值对，将一个对象赋予了一个新键\n",
    "# 1、如果这个key值不存在，则向字典中增加该键值对\n",
    "# 2、如果这个key值存在，则更新它的value为=后面的新值\n",
    "person4={\"Name\":\"游鸽\",\"Gender\":\"Male\"}\n",
    "person4\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': '游鸽', 'Gender': 'Male', 'Age': 30}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person4['Age'] = 30\n",
    "person4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典中如何更新一个存在的键值对的键值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': '小宋', 'Gender': 'Male'}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#给字典中已有的键值对赋予一个新值 ，就把原字典中的已有的键值对更新了\n",
    "person4={\"Name\":\"游鸽\",\"Gender\":\"Male\"}\n",
    "person4[\"Name\"]=\"小宋\"\n",
    "person4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': '游鸽', 'Gender': 'Male', 'Occupation': 'Researcher'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#可以先创建一个空字典，不断的增加键值对来更新字典，得到我们想要的字典\n",
    "person3 = {}\n",
    "person3[\"Name\"]=\"游鸽\"\n",
    "person3[\"Gender\"]=\"Male\"\n",
    "person3[\"Occupation\"]=\"Researcher\"\n",
    "person3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典的频度计数引用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n",
      "{'a': 0, 'e': 1, 'i': 0, 'o': 0, 'u': 0}\n",
      "{'a': 0, 'e': 2, 'i': 0, 'o': 0, 'u': 0}\n"
     ]
    }
   ],
   "source": [
    "#频度计数器先将频数初始化为0\n",
    "found={}\n",
    "found[\"a\"]=0\n",
    "found[\"e\"]=0                    #原字典\n",
    "found[\"i\"]=0\n",
    "found[\"o\"]=0\n",
    "found[\"u\"]=0\n",
    "print(found)\n",
    "found[\"e\"]=found[\"e\"]+1\n",
    "print(found)                                #两种方式递增e的频度计数\n",
    "found[\"e\"]+=1\n",
    "print(found)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 迭代处理字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n",
      "a\n",
      "e\n",
      "i\n",
      "o\n",
      "u\n"
     ]
    }
   ],
   "source": [
    "#需要使用一个for循环来使用字典\n",
    "found={}\n",
    "found[\"a\"]=0\n",
    "found[\"e\"]=0                    \n",
    "found[\"i\"]=0\n",
    "found[\"o\"]=0\n",
    "found[\"u\"]=0\n",
    "print(found)\n",
    "for kv in found:\n",
    "    print(kv)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n",
      "a is found 0 time(s).\n",
      "e is found 0 time(s).\n",
      "i is found 0 time(s).\n",
      "o is found 0 time(s).\n",
      "u is found 0 time(s).\n"
     ]
    }
   ],
   "source": [
    "print(found)\n",
    "for kv in found:\n",
    "    print(kv,\"is found\",found[kv],\"time(s).\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 迭代处理字典(2) –sorted()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n",
      "dict_items([('a', 0), ('e', 0), ('i', 0), ('o', 0), ('u', 0)])\n",
      "a is found 0 time(s).\n",
      "e is found 0 time(s).\n",
      "i is found 0 time(s).\n",
      "o is found 0 time(s).\n",
      "u is found 0 time(s).\n"
     ]
    }
   ],
   "source": [
    "#Sorted()内置方法不会改变你提供的数据的顺序，它只是返回这个数据的一个有序的副本\n",
    "print(found)\n",
    "print(found.items())\n",
    "for k,v in sorted(found.items()):\n",
    "    print(k,\"is found\",v,\"time(s).\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 迭代处理字典—案例\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入一个只带字母的字符串aigoydhs\n",
      "a is found 1 time(s)\n",
      "e is found 0 time(s)\n",
      "i is found 1 time(s)\n",
      "o is found 1 time(s)\n",
      "u is found 0 time(s)\n"
     ]
    }
   ],
   "source": [
    "#书上的一个程序案例，随机输入一个只含字母的随机字符串，统计其中a、e、i、o、u字符的数量，使用字典的频度计数来设计程序\n",
    "voles=[\"a\",\"e\",\"i\",\"o\",\"u\"]\n",
    "word = input(\"请输入一个只带字母的字符串\")\n",
    "found = {}\n",
    "found[\"a\"]=0\n",
    "found[\"e\"]=0                    \n",
    "found[\"i\"]=0\n",
    "found[\"o\"]=0\n",
    "found[\"u\"]=0\n",
    "for i in word:\n",
    "    if i in voles:\n",
    "        found[i]+=1\n",
    "for k,v in sorted(found.items()):\n",
    "    print(k,\"is found\",v,\"time(s)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典中 in与not in的用法"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "* 可以用 in 操作符来检查一个字典中是否存在这个键，这样可以有效的避免字典取值时出现的keyerror\n",
    ">>> 'apples' in d\n",
    "True\n",
    ">>> 'oranges' in d\n",
    " False\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "一般程序员用not in 来判断键是否在字典中，若不在初始化一个0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典中的setdefault() 方法\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apples': 10, 'bananas': 1}\n"
     ]
    }
   ],
   "source": [
    "#setdefault( key, value)的表示行书\n",
    "#setdefaut 是完成2行if / not in 语句所做的工作，不过用的是一行代码\n",
    "fruits={}\n",
    "fruits[\"apples\"]=10\n",
    "if \"bananas\" not in fruits:\n",
    "    fruits[\"bananas\"]=0\n",
    "fruits[\"bananas\"]+=1\n",
    "print(fruits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apples': 10, 'bananas': 3}\n"
     ]
    }
   ],
   "source": [
    "fruits.setdefault(\"bananas\",0)\n",
    "fruits[\"bananas\"]+=1                         #等同以上\n",
    "print(fruits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
